(function($, window, document) {

	$.fn.grid = function(options) {
		var o = $.extend({}, {
			id : "",
			idFieldName : "",
			processKey : undefined,
			url : "",
			datatype : "json",
			mtype : "",
			adSearchTb : "AdSearchTb",
			columnFilterVal : false,
			editurl : null,
			autowidth : true,
			width : null,
			height : null,
			colNames : null,
			colModel : null,
			rowList : null,
			rowNum : null,
			rownumbers : null,
			viewrecords : true,
			forceFit : true,
			sortname : "",
			sortorder : "",
			altRows : true,
			multiselect : null,
			loadonce : null,
			hiddengrid : null,
			gridview : null,
			shrinkToFit : null,
			postData : null,
			actions : {
				showToolbar : true,
				showSearchbar : true,
				configColumns : false,
				cusFormatterActions : true,
				cusActions : null,
				actionsWidth : 80,
				excelExportUrl : null,
				cusEditUrl : null,
				cusViewUrl : null,
				cusDeleteUrl : null,
				beforeCreateAction : null,
				afterActionsSuccess : null,
				autoReloadTreeMenu : null,
				autoReloadGrid : false,
				cusEditText : undefined
			},
			cusDialog : {
				cusDialogWidth : null,
				cusDialogHeight : null,
				cusDialogSize : null,
				cusDialogMax : null,
				onThisWindow : false
			},
			groupHeaders : null,
			cusGroup : {
				grouping : false,
				groupField : ""
			},
			loadComplete : null
		}, options);

		if (o.processKey) {
			o.actions.cusEditText = "处理";
		} else {
			o.actions.cusEditText = "编辑";
		}

		var self = this, $element = $(this), _create = function(o) {

			$result.jqGrid = _createGrid(o.colNames, o.colModel);

			// var adSearchElementId = o.id + o.adSearchTb;
			// isperp.initElement("#" + adSearchElementId);
			if (o.autowidth)
				$(window).resize(function() {
					$result.resizeGridDelay();
				});

			if (o.groupHeaders) {
				$result.jqGrid.setGroupHeaders({
					useColSpanStyle : true,
					groupHeaders : o.groupHeaders
				});
			}

		}, _actions = function(rowObject, ifCreateEditBtn, ifCreateDeleteBtn) {

			var act = o.actions, actions = "";
			if (act.cusActions) {
				actions += act.cusActions(rowObject);
			}
			if (act.cusViewUrl) {

				actions += isperp.createGridAction({
					title : "查看",
					iconCls : "icon-view",
					onclick : o.id + ".view('" + rowObject[o.idFieldName] + "')"
				});
			}
			if (act.cusEditUrl && ifCreateEditBtn) {
				actions += isperp.createGridAction({
					title : o.actions.cusEditText,
					iconCls : "ui-icon-pencil",
					onclick : o.id + ".edit('" + rowObject[o.idFieldName] + "')"
				});
			}
			if (act.cusDeleteUrl && ifCreateDeleteBtn) {
				actions += isperp.createGridAction({
					title : "删除",
					iconCls : "ui-icon-trash",
					onclick : o.id + ".deleteItem('" + rowObject[o.idFieldName] + "')"
				});
			}

			return "<span class='ui-pg-div ui-inline-action'></span>" + actions;
		}, _openDialog = function(title, url) {

			if (isperp.openDialog)
				isperp.openDialog({
					onThisWindow : o.cusDialog.onThisWindow,
					title : title,
					width : o.cusDialog.cusDialogWidth,
					height : o.cusDialog.cusDialogHeight,
					windowSize : o.cusDialog.cusDialogSize,
					max : o.cusDialog.cusDialogMax,
					contentUrl : url
				});

		}, _createGrid = function(colNames, colModel, islocal, opt) {
			// colNames优先级更高
			if (opt)
				$.extend(o, opt);
			var oselectColumns = '';
			if (colNames) {

				$(colModel).each(function(index, item) {
					oselectColumns += ',' + item.name;
				});

			} else {
				colNames = new Array(), colModel = new Array();

				if (o.actions.configColumns || (o.actions.showToolbar && o.actions.showSearchbar)) {
					$.ajax({
						url : "app/userDefGrid/findUserDefGrid",
						type : 'GET',
						async : false,
						cache : false,
						data : {
							url : window.location.pathname.substr(isperp.webPath.length),
							gridId : o.id
						},
						dataType : 'json',
						success : function(result) {

							var cclomodels = JSON.parse(result.col_model), clen = cclomodels.length;
							if (clen > 0) {
								o.rowNum = parseInt(result.page_size);
								var icclomodels = new Array();

								$(o.actions.cusColModel).each(function(iindex, iitem) {
									if (iitem.hidden) {
										icclomodels.push(iitem);
									} else {
										for ( var i = 0; i < clen; i++) {
											if (cclomodels[i].name == iitem.name) {
												iitem.showInHead = cclomodels[i].showInHead;
												icclomodels.push(iitem);
												return true;
											}
										}
										icclomodels.push(iitem);
									}
								});

								o.actions.cusColModel = icclomodels;
							}
						}
					});
				}

				$(o.actions.cusColModel).each(function(index, item) {
					if (item.showInHead) {
						colNames.push(item.label);
						colModel.push(item);
						oselectColumns += ',' + item.name;
					}
				});
			}

			$.extend(o.postData, {
				'selectColumns' : oselectColumns.substring(1)
			});

			var urlExtScriptResult = "", pagerId = $element.attr("id") + "Pager";
			if (o.urlExtScript) {
				urlExtScriptResult = o.urlExtScript();
			}
			if (o.actions.cusFormatterActions != "false" && (o.actions.cusViewUrl || o.actions.cusEditUrl || o.actions.cusDeleteUrl || o.actions.cusActions)) {
				colNames.push('操作');
				var w = 0;
				var ifCreateDeleteBtn = true;
				var ifCreateEditBtn = true;
				// 控制编辑删除权限
				if (o.editOrDeleteRightControl) {
					if (o.actions.cusDeleteUrl && !isperp.getCurUserRight(encodeURIComponent(o.actions.cusDeleteUrl))) {
						ifCreateDeleteBtn = false;
					}
					if (o.actions.cusEditUrl && !isperp.getCurUserRight(encodeURIComponent(o.actions.cusEditUrl))) {
						ifCreateEditBtn = false;
					}
				}

				if (o.actions.cusViewUrl) {
					w += 30
				}
				if (o.actions.cusEditUrl) {
					w += 30
				}
				if (o.actions.cusDeleteUrl) {
					w += 30;
				}
				if (o.actions.actionsWidth < w) {
					o.actions.actionsWidth = w;
				}
				var actionDo = {
					name : '操作',
					align : 'left',
					width : o.actions.actionsWidth,
					fixed : true,
					frozen : true,
					sortable : false,
					search : false,
					formatter : function(cellvalue, options, rowObject) {
						return _actions(rowObject, ifCreateEditBtn, ifCreateDeleteBtn);
					}
				};
				colModel.push(actionDo);
			}
			var gridLoadUrl = encodeURI(o.url + urlExtScriptResult);
			var gOptions = {
				url : gridLoadUrl,
				datatype : islocal ? "local" : o.datatype,
				mtype : o.mtype,
				autowidth : o.autowidth,
				width : o.width,
				height : o.height,
				colNames : colNames,
				colModel : colModel,
				rowList : o.rowList,
				rowNum : o.rowNum,
				rownumbers : o.rownumbers,
				viewrecords : true,
				forceFit : true,
				sortname : o.sortname,
				sortorder : o.sortorder,
				altRows : o.altRows,
				altclass : "gridAltclass",
				multiselect : o.multiselect,
				loadonce : o.loadonce,
				hiddengrid : o.hiddengrid,
				gridview : o.gridview,
				shrinkToFit : o.shrinkToFit,
				postData : o.postData,
				jsonReader : {
					repeatitems : false,
					root : "content"
				},
				beforeRequest : function() {

					var d = $element.getGridParam("records");
					var postData = $element.jqGrid("getGridParam", "postData");
					if (d > 1)
						$.extend(postData, {
							records : d
						});
					else {
						$.extend(postData, {
							records : 0
						});
					}

					$result.isLoading = true;

				},
				loadComplete : function(data) {
					if (o.columnFilterVal) {
						$element.jqGrid('filterToolbar', {
							stringResult : true,
							searchOnEnter : true
						});
					}
					if (o.loadComplete) {
						o.loadComplete(data);
					}
					if (o.autowidth == false) {
						var gwidth = $element.jqGrid("getGridParam", 'width') || 0, dwidth = $("#" + o.id + "AdSearch").width();
						if (dwidth > gwidth) {
							$element.setGridWidth(dwidth - 10);
						}
					}
					if ($result.menu) {
						$result.menu.zTree.addNodes(data.menudata)
					}
					if (o.actions.autoReloadTreeMenu && data.menudata) {

						var slectedNode = o.actions.autoReloadTreeMenu.getSelectedNode(), slectedNodeId = undefined;

						var nodes = o.actions.autoReloadTreeMenu.zTree.getNodes();
						for ( var i = nodes.length - 1; i >= 0; i--) {
							o.actions.autoReloadTreeMenu.zTree.removeNode(nodes[i]);
						}
						o.actions.autoReloadTreeMenu.zTree.addNodes(undefined, data.menudata);

						if (slectedNode) {
							slectedNodeId = slectedNode.id;
						} else {
							slectedNodeId = data.menudata[0].id;
						}

						var nodes = o.actions.autoReloadTreeMenu.zTree.getNodes(), mlength = nodes.length;

						for ( var iid = 0; iid < mlength; iid++) {
							if (slectedNodeId == nodes[iid].id) {

								$.fn.zTree._z.view.selectNode(o.actions.autoReloadTreeMenu.zTree.setting, nodes[iid], false);
								break;
							}
						}
					}

				},
				gridComplete : function() {
					$result.isLoading = false;
				},
				ondblClickRow : function(rowid, iRow, iCol, e) {
					if (typeof o.ondbClickRowEvent == 'function')
						o.ondbClickRowEvent(rowid, iRow, iCol, e);
				},
				onSelectRow : function(rowid, status) {
					if (o.onSelectRow)
						o.onSelectRow(rowid, status);
				},
				onSelectAll : function(aRowids, status) {
					if (o.onSelectAll)
						o.onSelectAll(aRowids, status);
				},
				loadBeforeSend : function(xhr, settings) {
					if (o.autoload === false) {
						this.p.loadBeforeSend = null;
						return false;
					}
				},
				onRightClickRow : function(rowid, iRow, iCol, e) {
					var a = $result.jqGrid.getRowData(rowid)["操作"];
					$result.menuData.splice(0, $result.menuData.length);
					$(a).find(".ui-grid-action").each(function(index, item) {

						var item = $(item);

						$result.menuData[index] = [ {
							text : $(item).attr("title"),
							func : function() {
								$(item).click();
							}
						} ];
					});

				},
				pager : pagerId,
				toppager : false,
				cloneToTop : true,
				editurl : o.editurl
			};

			if (o.cusGroup && o.cusGroup.grouping == "true") {
				gOptions = $.extend({}, gOptions, {
					grouping : true,
					groupingView : {
						groupField : [ o.cusGroup.groupField ],
						groupColumnShow : [ false, false ]
					}
				});
			}

			var grid = $("#" + o.id).jqGrid(gOptions);

			$("#" + o.id).smartMenu($result.menuData, {
				textLimit : 10,
				beforeShow : function() {
					$.smartMenu.remove();
				}
			});
			// if (o.actions.cusDeleteUrl) {
			// pageLeft.append('<span title="删除" class="ui-pg-div
			// ui-inline-action"><span class="ui-icon ui-icon-trash"
			// onclick=""></span></span>')
			// }

			/*if (o.actions.configColumns || (o.actions.showToolbar && o.actions.showSearchbar))
				$("#" + o.id + "Pager_left").append('<span title="设置列" class="ui-pg-div ui-inline-action"><span class="ui-icon icon-config" onclick="' + o.id + '.setColModel()"></span></span>');
*/
			var cloadHtml = '&nbsp;&nbsp;<span title="刷新" class="ui-pg-div ui-inline-action"><a class="ui-icon icon-refresh" onclick="' + o.id + '.search()"></a></span>';

			if (o.actions.autoReloadGrid) {
				cloadHtml += '<input type="checkbox" onchange="' + o.id + '.setAutoReload()" id="' + o.id + 'AutoChk" name="' + o.id + 'AutoChk" checked="checked"><lable for="' + o.id + 'AutoChk"><span  id="' + o.id + 'AutoSec" style="color: #c00">60</span>秒后自动刷新</label>';
			}

			$("#" + o.id + "Pager_center td").last().append(cloadHtml);
			if (o.actions.autoReloadGrid) {
				$result.addAutoReloadTimer();
			}
			return grid;

		}, _afterSuccess = function() {
			if (o.actions.afterActionsSuccess) {
				o.actions.afterActionsSuccess(self, o);
			}
			$result.search();
		}, $result = {
			isLoading : true,
			menuData : [],
			resizeGridDelay : function() {
				var gwidth = $("#" + o.id + "AdSearch").width();
				if (gwidth > 200)
					$result.jqGrid.setGridWidth(gwidth - 2);

			},
			setAutoReload : function() {
				var item = document.getElementById(o.id + "AutoChk");
				if (item && $(item).is(":checked")) {
					$result.addAutoReloadTimer();
				} else {
					clearInterval($result.autoReloadPerTimer);
					$("#" + o.id + "AutoSec").html(60);
				}
			},
			resetAutoReloadTimer : function() {
				$result.autoReloadPerTimer

				clearInterval($result.autoReloadPerTimer);
				addAutoReloadTimer();
			},
			addAutoReloadTimer : function() {
				var sec = 60, $secLabel = $("#" + o.id + "AutoSec");
				$result.autoReloadPerTimer = window.setInterval(function() {

					sec--;
					if (sec == 0) {
						$result.search(undefined, false, true);
						sec = 60;
					}

					$secLabel.html(sec);

				}, 1000);
			},
			switchMoreSearch : function(obj) {
				var $o = $(obj), st = $o.data("st"), gelementId = $element.attr("id");
				$result.resetSearchFilters();
				if (st == "1") {
					$("#" + gelementId + "MoreSearch").show();

					$("#" + gelementId + "KeywordInputPanel").hide();

					$result.resetSearch(gelementId + "MoreSearch");
				} else {

					$("#" + gelementId + "MoreSearch").hide();

					$("#" + gelementId + "KeywordInputPanel").show();

					$result.resetSearch(gelementId + "KeywordInputPanel");
				}

			},
			resetSearch : function(elementId) {

				$("#" + elementId + " input[type='text'],#" + elementId + " select" + ",#" + elementId + " input[type='hidden']").each(function() {
					var $el = $(this);
					$el.val("");
					try {
						$el.trigger("chosen:updated");
					} catch (e) {
					}
				});

			},
			setColModel : function() {
				$result.dialog.dialog("open");
			},
			create : function(params) {
				var beforeCreateAction = o.actions.beforeCreateAction, beforeCreateActionResult = null;

				if (beforeCreateAction) {
					beforeCreateActionResult = beforeCreateAction();
					if (!beforeCreateActionResult) {
						return false;
					}
				}
				params = (params == undefined ? beforeCreateActionResult : (params + (beforeCreateActionResult ? "" : "&" + beforeCreateActionResult)));
				var url = o.actions.cusEditUrl;
				if (url.indexOf('?') != -1) {
					url += "&" + params;
				} else {
					url += "?" + params;
				}
				_openDialog("新建" + o.title, url + "&pcontrolid=" + o.id + "&randomv=" + 10000 * Math.random());
			},
			view : function(id) {

				var title = "";
				var rowObject = $result.jqGrid.getRowData(id);
				if (rowObject.code) {
					title += "【" + rowObject.code + "】";

				}
				if (rowObject.title) {
					title += "-" + rowObject.title;
				}

				var url = o.actions.cusViewUrl;
				if (url.indexOf('?') != -1) {
					url += "&id=" + id;
				} else {
					url += "?id=" + id;
				}
				_openDialog("查看" + title + o.title, url);
			},
			edit : function(id) {
				var beforeEditActionResult = null;
				var rowObject = $result.jqGrid.getRowData(id);
				var url = o.actions.cusEditUrl;
				if(rowObject.process_key && (rowObject.process_id==undefined || rowObject.process_id==""))
				{
					//如果是自定义流程，且还没发起流程，则需要获取自定义流程的开始表单
					var processKey=rowObject.process_key;
					$.ajax({
						url:'bpm/processSetting/getStartFormByProcDefKey?processKey='+processKey,
						async: false,
						success:function(data)
						{
							url=data;
						}
					});
				}
				$result.jqGrid.setSelection(id);
				if (typeof o.actions.beforeEditAction == 'function') {

					beforeEditActionResult = o.actions.beforeEditAction(id);
					if (!beforeEditActionResult) {
						return false;

					}
				}
				if (url.indexOf('?') != -1) {
					url += "&id=" + id;
				} else {
					url += "?id=" + id;
				}
				var title = "";
				var rowObject = this.getRowData(id);
				if (rowObject.code) {
					title += "【" + rowObject.code + "】";

				}
				if (rowObject.title) {
					title += "-" + rowObject.title;
				}
				_openDialog(o.actions.cusEditText + title + o.title, url + "&pcontrolid=" + o.id);

			},
			deleteItem : function(id) {
				if (o.actions.beforeDeleteAction) {
					beforeDeleteActionResult = o.actions.beforeDeleteAction(id);
					if (!beforeDeleteActionResult) {
						return false;
					}
				}
				var cusDeleteActionUrl = o.actions.cusDeleteUrl;
				isperp.confirmAlert('确定删除？<label style="color:red">（数据被删除后无法恢复！）', {
					yes : function() {
						$.post(cusDeleteActionUrl, {
							id : id
						}, function(data, textStatus) {
							if (data.success) {
								isperp.tooltip("删除成功！");
								isperp.reloadParentControl();
								_afterSuccess();
							} else {
								isperp.alert(data.data);
							}
						}, "json");
					}
				});

			},
			excelExport : function() {
				var excelExportUrl = $result.jqGrid.getGridParam("url");
				if (excelExportUrl == "") {
					isperp.alert("请配置导出路径！");
					return false;
				}

				var colModel = $result.jqGrid.getGridParam("colModel"), eocolName = '';
				$(colModel).each(function(index, item) {
					if (item.name != "rn")
						eocolName += "," + item.label
				});
				$result.jqGrid.jqGrid("excelExport", {
					url : isperp.webPath + "/exportExcel",
					mtype : 'POST',
					exportOptions : eocolName.substring(1) + ";" + excelExportUrl
				});
				return false;
			},
			reload : function(otherfilter) {
				this.search(otherfilter, false, true);
			},
			resetSearchFilters : function() {
				$result.jqGrid[0].p.postData.filters = "";
			},

			getSearchFilters : function(otherfilter) {
				var grid = $result.jqGrid, adSearchElement = "#" + $element.attr("id") + o.adSearchTb;

				if (!grid) {
					return;
				}
				var myfilterRules = [];
				if (otherfilter != undefined) {
					$(otherfilter).each(function(index, item) {
						myfilterRules.push(item);
					});
				}

				var filtersStr = grid[0].p.postData.filters;
				var filters = [];
				if (filtersStr) {
					filters = JSON.parse(filtersStr).rules;
				}

				// 针对checkbox特殊处理
				var checkboxInStr = "";
				var checkboxInFiled = "";
				var checkboxUnchecknum = 0;

				$(adSearchElement + " input," + adSearchElement + " select").each(function() {
					var el = $(this);
					var fv = el.val();

					if (el.attr("type") == "checkbox") {
						fv = el.attr("data-code");
						checkboxInFiled = el.attr("field");
					}

					if (fv && fv != "" && fv != undefined && el.attr("field") && el.attr("field") != "" && el.attr("field") != undefined) {
						if (el.is(":radio") || el.is(":checkbox")) {
							if (el.is(":checked")) {
								if (el.attr("type") == "checkbox" && el.attr("op") == "in") {
									checkboxInStr += "'" + fv + "',";
								} else {
									myfilterRules.push({
										"field" : el.attr("field"),
										"op" : el.attr("op"),
										"data" : fv,
										"type" : (el.hasClass("hasDatepicker") || el.hasClass("date")) ? 3 : 0
									});
								}

							} else if (!el.is(":checked") && el.attr("type") == "checkbox") {
								checkboxUnchecknum = checkboxUnchecknum + 1;
							}
						} else {
							var top = el.attr("op");
							// 如果操作符是in，需要检查value格式是否正确
							if (top == "in") {
								if ((fv.indexOf(",") > 0) && (fv.indexOf("'") < 0)) {
									var tfv_arr = fv.split(",");
									var tfv = "";
									for ( var j = 0; j < tfv_arr.length; j++) {
										tfv += "'" + tfv_arr[j] + "',";
									}
									tfv = tfv.substring(0, tfv.length - 1);
									fv = tfv;
								}
							}

							myfilterRules.push({
								"field" : el.attr("field"),
								"op" : top,
								"data" : fv,
								"type" : (el.hasClass("hasDatepicker") || el.hasClass("date")) ? 3 : 0
							});
						}
					} else {
						if (filters.length > 0) {
							var field = el.attr("field");
							var dindex = -1;
							for ( var i = 0; i < filters.length; i++) {
								if (filters[i].field == field) {
									dindex = i;
									break;
								}
							}
							if (dindex >= 0) {
								for ( var i = 0, n = 0; i < filters.length; i++) {
									if (filters[i] != filters[dindex]) {
										filters[n++] = filters[i]
									}
								}
								filters.length -= 1;
							}
						}
					}
				});

				if (checkboxInStr != "" && checkboxUnchecknum != 0) {
					checkboxInStr = checkboxInStr.substring(0, checkboxInStr.length - 1);
					myfilterRules.push({
						"field" : checkboxInFiled,
						"op" : "in",
						"data" : checkboxInStr,
						"type" : 10
					});

				}

				grid[0].p.search = (myfilterRules.length + filters.length) > 0;
				if (filters.length > 0) {
					var resultFilter = myfilterRules;
					for ( var i = 0; i < filters.length; i++) {
						var finded = false;
						for ( var j = 0; j < myfilterRules.length; j++) {
							if (myfilterRules[j].field == filters[i].field) {
								finded = true;
								break;
							}
						}
						if (!finded && filters[i].type != 10) {
							resultFilter.push(filters[i]);
						}
					}
					grid[0].p.postData.filters = JSON.stringify({
						"groupOp" : "AND",
						rules : resultFilter
					});
				} else {
					$.extend(grid[0].p.postData, {
						filters : JSON.stringify({
							"groupOp" : "AND",
							rules : myfilterRules
						})
					});
				}
				return $result.jqGrid[0].p.postData.filters;
			},
			search : function(otherfilter, notMenu, noChangePage) {
				var grid = $result.jqGrid;
				var postData = grid.jqGrid("getGridParam", "postData"), _pageNo = noChangePage ? grid.getGridParam('page') : 1;

				$.extend(postData, {
					notMenu : ((notMenu || !o.actions.autoReloadTreeMenu) ? true : false)
				});

				this.getSearchFilters(otherfilter);
				grid.setGridParam({
					datatype : 'json'
				}).trigger("reloadGrid", [ {
					page : _pageNo
				} ]);
			},
			selrow : function() {
				return $element.jqGrid("getGridParam", "selrow");
			},
			getRowData : function(selectedId) {
				selectedId = selectedId || $element.jqGrid("getGridParam", "selrow");
				if (selectedId)
					return $element.jqGrid("getRowData", selectedId);
				return null;
			},
			createGrid : function(colNames, colModel, islocal, opt) {
				$result.jqGrid = _createGrid(colNames, colModel, islocal, opt);

				return $result.jqGrid;
			},
			configColumns : function(saveConfig) {
				var cnames = new Array(), ccols = new Array(), cclomodels = new Array();
				$("#" + o.id + "_columns .ui-jqgrid-cc-i").each(function(index, item) {
					var $item = $(item), _isCheck = $item.is(":checked"), cname = $(item).data("name");
					$(o.actions.cusColModel).each(function(index, item) {
						if (cname == item.name) {
							item.label = item.label;
							if (_isCheck) {
								cnames.push(item.label);
								ccols.push(item);
							}
							cclomodels.push({
								showInHead : _isCheck,
								name : item.name,
								label : item.label
							});
							return;
						}
					});

				});

				if (saveConfig) {
					$.ajax({
						url : "app/userDefGrid/save",
						type : 'POST',
						data : {
							url : window.location.pathname.substr(isperp.webPath.length),
							gridId : o.id,
							pageSize : $("#" + o.id).jqGrid('getGridParam', "rowNum"),
							colModel : JSON.stringify(cclomodels)
						},
						dataType : 'json',
						success : function() {

						}
					});
				}
				var postData = $result.jqGrid.jqGrid("getGridParam", "postData");
				$result.jqGrid.GridUnload();
				$result.jqGrid = $result.createGrid(cnames, ccols, true);

				if (postData.queryPath) {
					var postData2 = $result.jqGrid.jqGrid("getGridParam", "postData");
					$.extend(postData2, {
						queryPath : postData.queryPath
					});
				}

				$result.search();
			},
			changeColumnCheck : function() {
				var item = document.getElementById(o.id + "_chkall");

				if (item && $(item).is(":checked")) {

					$("#" + o.id + "_columns input").each(function() {
						$(this).prop("checked", true);
					});
					$("#" + o.id + "_forchkall").text("取消选择所有列");
				} else {
					$("#" + o.id + "_columns input").each(function() {
						$(this).prop("checked", false);
					});

					$("#" + o.id + "_forchkall").text("选择所有列");
				}
			},
			resetColumnCheck : function() {
				$.ajax({
					url : "app/userDefGrid/deleteUserDefGrid",
					type : 'GET',
					async : false,
					cache : false,
					data : {
						url : window.location.pathname.substr(isperp.webPath.length),
						gridId : o.id
					}
				});
				$result.dialog.dialog("close");
				$result.jqGrid.GridUnload();
				$result.createGrid();

				$("#" + o.id + "_columns .ui-jqgrid-cc-i").each(function(index, item) {

					$(o.actions.cusColModel).each(function(index2, item2) {
						var $item = $(item);
						if ($item.data("name") == item2.name) {
							if (item2.showInHead) {
								$item.prop("checked", true);

							} else {
								$item.prop("checked", false);
							}
							return false;
						}

					});
				});

				$("#" + o.id + "_chkall").prop("checked", false);
				$("#" + o.id + "_forchkall").text("选择所有列");

			}
		};
		_create(o);

		var shtmlv = "";

		$(o.actions.cusColModel).each(function(index, item) {
			if (item.hidden || item.label == '') {
				shtmlv += "<li class='ui-jqgrid-cc'none style='display:none'><input type='checkbox' class='ui-jqgrid-cc-i' id='gcc_" + item.name + "' data-name='" + item.name + "' ";
				shtmlv += " checked='checked'></li>";
			} else {
				shtmlv += "<li class='ui-jqgrid-cc'><input type='checkbox' class='ui-jqgrid-cc-i' id='gcc_" + item.name + "' data-name='" + item.name + "' ";
				if (item.showInHead) {
					shtmlv += " checked='checked' ";
				}
				shtmlv += "><label for='gcc_" + item.name + "'>" + item.label + "</label></li>";
			}
		});

		$("#" + o.id + "_columns").html(shtmlv);

		$("#" + o.id + "_columns").sortable({
			connectWith : ".ui-jqgrid-cc",
			opacity : "0.6",
			dropOnEmpty : true
		}).disableSelection();

		$result.dialog = $("#" + o.id + "_columnsDialog").dialog({
			autoOpen : false,
			width : 480,
			dialogClass : o.id + "_class",
			height : (Math.ceil(o.actions.cusColModel.length / 4) * 42),
			create : function() {

				$("." + o.id + "_class .ui-grid-button-left").after("<div  style='float:left;padding:5px'><input type='checkbox'  id='" + o.id + "_chkall' onclick='" + o.id + ".changeColumnCheck()'><label for='" + o.id + "_chkall' id='" + o.id + "_forchkall'>选择所有列</label>&nbsp;&nbsp;<a onclick='" + o.id + ".resetColumnCheck()' style='cursor:pointer'>恢复默认列</a></div>");

			},
			buttons : [ {
				text : "导出",
				click : function() {
					var records = $result.jqGrid.getGridParam('records');

					if (records > 15000) {
						isperp.alert("您导出的数据量过大，请查询后再导出！");
						return false;
					}

					$result.configColumns();
					$result.excelExport();
				},
				"class" : 'ui-grid-button-left'
			}, {
				text : "确定",
				"class" : "nui-mainbtn",
				click : function() {
					$result.configColumns(true);
					$(this).dialog("close");
				}
			}, {
				text : "关闭",
				click : function() {
					$(this).dialog("close");
				}
			} ]

		});

		return $result;
	}

})(jQuery, this, document);
